<template>
  <basic-container class="user">
    <div class="user__containter flex">
      <div class="user__tree">
        <avue-tree
          ref="tree"
          :option="treeOption"
          :data="treeData"
          @node-click="nodeClick"
        >
        </avue-tree>
      </div>
      <div class="user__main flex-1">
        <avue-crud
          ref="crud"
          v-model="form"
          :option="option"
          :page.sync="page"
          :search.sync="searchForm"
          :table-loading="tableLoading"
          :before-open="handleOpenBefore"
          :data="tableData"
          @on-load="getList"
          @search-change="searchChange"
          @row-update="update"
          @row-save="create"
          @search-reset="resetChange"
        >
          <template slot="menuLeft">
            <el-button
              v-if="sys_user_add"
              class="filter-item"
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="$refs.crud.rowAdd()"
            >
              添加
            </el-button>
          </template>
          <template
            slot="username"
            slot-scope="scope"
          >
            <span>{{ scope.row.username }}</span>
          </template>
          <template
            slot="role"
            slot-scope="scope"
          >
            <span
              v-for="(r, index) in scope.row.roleList"
              :key="index"
            >
              <el-tag>{{ r.roleName }} </el-tag>&nbsp;&nbsp;
            </span>
          </template>
          <template
            slot="post"
            slot-scope="scope"
          >
            <span
              v-for="(p, index) in scope.row.postList"
              :key="index"
            >
              <el-tag>{{ p.postName }} </el-tag>&nbsp;&nbsp;
            </span>
          </template>
          <template
            slot="lockFlag"
            slot-scope="scope"
          >
            <el-tag>{{ scope.label }}</el-tag>
          </template>
          <template
            slot="menu"
            slot-scope="scope"
          >
            <el-button
              v-if="sys_user_edit"
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row, scope.index)"
            >编辑
            </el-button>
            <el-button
              v-if="sys_user_del"
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="deletes(scope.row, scope.index)"
            >删除
            </el-button>
          </template>
          <!-- <template slot="roleForm">
            <avue-select
              v-model="role"
              :dic="rolesOptions"
              :props="roleProps"
              multiple
              placeholder="请选择角色"
            />
          </template> -->
        </avue-crud>
      </div>
    </div>

    <!--excel 模板导入 -->
    <excel-upload
      ref="excelUpload"
      title="用户信息导入"
      url="/admin/user/import"
      temp-url="/admin/sys-file/local/file/user.xlsx"
      @refreshDataList="refreshChange"
    ></excel-upload>
    <!-- <excel-upload
          ref="excelDingUserUpload"
          title="钉钉用户信息导入"
          url="/admin/user/importDingUser"
          @refreshDataList="refreshChange"
        ></excel-upload>
        <excel-upload
          ref="excelCpUserUpload"
          title="企业微信用户信息导入"
          url="/admin/user/importCpUser"
          @refreshDataList="refreshChange"
        ></excel-upload> -->
  </basic-container>
</template>

<script>
// import { listPosts } from '@/api/admin/post';
import {
  addObj,
  delObj,
  fetchList,
  putObj,
  getObj,
  getPublicWelfareStationByUserId,
} from '@/api/admin/user';
// import { deptRoleList } from '@/api/admin/role';
import { fetchBaseList } from '@/api/core/base';
import { tableOption } from '@/const/crud/admin/user';
import { mapGetters } from 'vuex';
import ExcelUpload from '@/components/upload/excel';
import crudMixins from '@/mixins/crud';
import { USER_TYPE } from '@/const/type';
export default {
  name: 'SysUser',
  components: {
    ExcelUpload,
  },
  mixins: [crudMixins],
  data() {
    return {
      treeOption: {
        nodeKey: 'id',
        addBtn: false,
        menu: false,
        props: {
          label: 'name',
          value: 'id',
        },
      },
      treeData: [],
      option: tableOption(),
      // treeDeptData: [],
      // checkedKeys: [],
      // defaultProps: {
      //   label: 'name',
      //   value: 'id',
      // },
      role: [],
      form: {},
      baseId: '',
      excelUpload: false,
    };
  },
  computed: {
    ...mapGetters(['permissions']),
  },
  watch: {
    role() {
      this.form.role = this.role;
    },
    'form.type'() {
      // 如果类型是平台，那么baseId为空
      if (this.form.type === USER_TYPE.PLATFORM) {
        this.form.baseIds = [];
      }
    },
  },
  created() {
    this.sys_user_add = this.permissions['sys_user_add'];
    this.sys_user_edit = this.permissions['sys_user_edit'];
    this.sys_user_del = this.permissions['sys_user_del'];
    this.init();
  },
  methods: {
    init() {
      fetchBaseList().then((response) => {
        this.treeData = [{ id: 0, name: '平台' }].concat(response.data.data);
      });
    },
    nodeClick(data) {
      this.page.page = 1;
      if (data.id === 0) {
        this.baseId = '';
        this.type = USER_TYPE.PLATFORM;
      } else {
        this.baseId = data.id;
        this.type = USER_TYPE.BASE;
      }
      this.getList(this.page);
    },
    getList(page = this.page, params = this.searchForm) {
      this.tableLoading = true;
      fetchList({
        current: page.currentPage,
        size: page.pageSize,
        ...params,
        baseId: this.baseId,
        type: this.type,
        ...this.searchForm,
      }).then((response) => {
        this.tableData = response.data.data.records;
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      });
    },
    // getNodeData() {
    //   deptRoleList().then((response) => {
    //     this.rolesOptions = response.data.data;
    //   });
    //   listPosts().then((response) => {
    //     this.postOptions = response.data.data;
    //   });
    // },
    async handleOpenBefore(show, type) {
      window.boxType = type;
      // 查询部门树
      // fetchTree().then((response) => {
      //   this.treeDeptData = response.data.data;
      // });
      // 查询角色列表
      // deptRoleList().then((response) => {
      //   this.rolesOptions = response.data.data;
      // });
      // // 查询岗位列表
      // listPosts().then((response) => {
      //   this.postOptions = response.data.data;
      // });
      if (['edit', 'view'].includes(type)) {
        const { data } = await getObj(this.form.userId);
        this.form = data.data;
        this.role = [];
        for (let i = 0; i < data.data.roleList.length; i++) {
          this.role[i] = data.data.roleList[i].roleId;
        }
        this.form.password = '******';
        // this.post = [];
        // for (let i = 0; i < this.form.postList.length; i++) {
        //   this.post[i] = this.form.postList[i].postId;
        // }
        if (this.form.type === USER_TYPE.BASE) {
          const res = await getPublicWelfareStationByUserId(this.form.userId);
          this.form.baseIds = res.data.data.map((el) => el.id);
        }
      } else if (type === 'add') {
        this.role = [];
        // this.post = [];
        this.form.username = undefined;
        this.form.phone = undefined;
        this.form.password = undefined;
      }
      show();
    },
    handleUpdate(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    create(row, done, loading) {
      if (this.form.phone && this.form.phone.indexOf('*') > 0) {
        this.form.phone = undefined;
      }
      addObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify.success('创建成功');
        })
        .catch(() => {
          loading();
        });
    },
    update(row, index, done, loading) {
      if (this.form.phone && this.form.phone.indexOf('*') >= 0) {
        this.form.phone = undefined;
      }
      if (this.form.password && this.form.password.indexOf('******') >= 0) {
        this.form.password = undefined;
      }
      putObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify.success('修改成功');
        })
        .catch(() => {
          loading();
        });
    },
    deletes(row, index) {
      this.$confirm(
        '此操作将永久删除该用户(用户名:' + row.username + '), 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.tableData.splice(index, 1);
            this.$notify.success('删除成功');
          })
          .catch(() => {
            this.$notify.error('删除失败');
          });
      });
    },
    exportExcel() {
      this.downBlobFile('/admin/user/export', this.searchForm, 'user.xlsx');
    },
    resetChange() {
      this.baseId = '';
      this.type = '';
      this.$refs.tree.setCurrentKey(null);
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped>
.user {
  ::v-deep {
    .el-card__body {
      overflow: hidden;
    }
  }

  &__containter {
    height: 100%;
  }

  &__tree {
    width: 300px;
    padding-top: 3px;
    padding-right: 20px;
    box-sizing: border-box;
    height: 100%;
    flex-shrink: 0;
    ::v-deep {
      .el-tree-node__content {
        height: 40px;
      }
      .el-tree-node__label {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  &__main {
    overflow: auto;
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>
